﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mortgage.DAL.Entity;
using Mortgage.Srv.Cls;
using System.Web.Security;
using System.Text;

namespace Mortgage.Form
{
    public partial class BillUI : System.Web.UI.Page
    {
        Mortgage.Srv.IMortgageSrv svcMortgage = Mortgage.Srv.SrvFactory.CreateMortgageSrv();
        Mortgage.Srv.IBillSrv svcBill = Mortgage.Srv.SrvFactory.CreateBillSrv();

        int mortgageId;

        protected void Page_Load(object sender, EventArgs e)
        {
            mortgageId = Convert.ToInt32(Request.QueryString["MorgId"]);
            EntityMorgate = svcMortgage.GetById(mortgageId);
            BindViewMortgage();
            if (!Page.IsPostBack)
            {
                RefreshDataGrid();
                BindMortStatusForBill();
                BindCalculateMethod();
                HandleFormStateBill(EnmFormMode.Blank);

            }
        }

        protected void grid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(grid.DataKeys[grid.SelectedIndex].Value.ToString());
            tBill bill = svcBill.GetById(id);
            if (bill == null)
                EntityBill = new tBill();
            else
                EntityBill = bill;

            // Update mode
            FormModeBill = EnmFormMode.View;
            HandleFormStateBill(FormModeBill);
            BindViewBill();
        }

        protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grid, "Select$" + e.Row.RowIndex);
            }
        }

        protected void chkCalculate_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void fldBillDate_TextChanged(object sender, EventArgs e)
        {
            BuilCalculateFormula();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormModeBill = EnmFormMode.Blank;
            HandleFormStateBill(FormModeBill);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            BindEntityBill();
            svcBill.Delete(EntityBill);
            RefreshDataGrid();
            FormModeBill = EnmFormMode.Blank;
            HandleFormStateBill(FormModeBill);
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            // Update mode
            EntityBill = new tBill() { ID = 0, BillDate = DateTime.Now, CalType = (int)EnmBillCalculateType.Week, BillType = (int)EnmMortgageStatus.Done };
            FormModeBill = EnmFormMode.Insert;
            HandleFormStateBill(FormModeBill);

            BindViewBill();
            BuilCalculateFormula();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            BindEntityBill();
            // clear error Message
            DialogMess.Text = string.Empty;
            DialogMess.CssClass = "successBox";
            int result;
            EnmMortgageStatus status = (EnmMortgageStatus)Enum.Parse(typeof(EnmMortgageStatus), rdoMortStatus.SelectedValue);

            if (FormModeBill == EnmFormMode.Insert) // Insert Mode
            {

                try
                {
                    result = svcBill.Insert(EntityBill, status);
                    switch (result)
                    {
                        case 0:
                            DialogMess.Text = "Cập nhật thành công!";
                            RefreshDataGrid();

                            // Translate to update mode
                            // Update mode
                            FormModeBill = EnmFormMode.Edit;
                            HandleFormStateBill(FormModeBill);
                            BindViewBill();
                            fldStatus.Text = Utility.GetMorgageStatusCode(Convert.ToInt32(rdoMortStatus.SelectedValue));
                            break;
                        default:
                            DialogMess.Text = "Số hóa đơn đã tồn tại";
                            DialogMess.CssClass = "failureBox";
                            break;

                    }

                }
                catch (Exception ex)
                {
                    DialogMess.Text = ex.Message;
                    DialogMess.CssClass = "failureBox";
                }


            }
            else
            {
                result = svcBill.Update(EntityBill, status);
                switch (result)
                {
                    case 0:
                        DialogMess.Text = "Cập nhật thành công!";
                        //BindGridView();

                        // Translate to update mode
                        // Update mode
                        FormModeBill = EnmFormMode.Edit;
                        HandleFormStateBill(FormModeBill);
                        BindViewBill();
                        fldStatus.Text = Utility.GetMorgageStatusCode(Convert.ToInt32(rdoMortStatus.SelectedValue));
                        break;
                    default:
                        DialogMess.Text = "Số hóa đơn đã tồn tại";
                        DialogMess.CssClass = "failureBox";
                        break;

                }
            }


            RefreshDataGrid();

        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            BindEntityBill();
            FormModeBill = EnmFormMode.Edit;
            HandleFormStateBill(FormModeBill);

        }

        #region Property

        public tMortgage EntityMorgate
        {
            get;
            set;


        }

        public tBill EntityBill
        {
            get;
            set;

        }

        public EnmFormMode FormModeBill
        {
            get
            {
                if (ViewState["_ViewStateBill"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewStateBill"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewStateBill"] = value;
            }
        }

        #endregion

        #region Bind Bill function

        protected void BuilCalculateFormula()
        {
            if (!string.IsNullOrEmpty(fldBillDate.Text) && !string.IsNullOrEmpty(chkCalculate.SelectedValue))
            {

                EnmBillCalculateType calType = (EnmBillCalculateType)Enum.Parse(typeof(EnmBillCalculateType), chkCalculate.SelectedValue);
                DateTime BillDate = Convert.ToDateTime(fldBillDate.Text);
                if (EntityBill != null)
                {
                    decimal calTotal = 0;
                    DateTime parCal = (FormModeBill == EnmFormMode.Insert ? DateTime.MaxValue : BillDate);
                    DateTime caldate = svcBill.GetDateBeginMortgage(mortgageId, parCal);

                    lblDateBeginCall.Text = Utility.FormatDateTime(caldate);

                    lblCalculateResult.Text = Mortgage.Srv.CalculateHelper.BuildCalculateFomula(caldate, BillDate, calType, EntityMorgate.InterestRate.GetValueOrDefault(), out calTotal);
                    lblCalculateResult.Text = lblCalculateResult.Text + " x ";
                    lblCalMortMone.Text = Utility.FormatMoney( EntityMorgate.MorMoney);
                    lblCalTotal.Text = Utility.FormatMoney((EntityMorgate.MorMoney * calTotal));

                    lblCalculateFomulaAll.Text = lblCalculateFomula.Text;
                    lblCalculateResultAll.Text = lblCalculateResult.Text;
                    lblCalMortMoneAll.Text = lblCalMortMone.Text + "+" + lblCalMortMone.Text;
                    lblCalTotalAll.Text = Utility.FormatMoney((EntityMorgate.MorMoney * calTotal + EntityMorgate.MorMoney));


                }
            }
        }

        protected void BindCalculateMethod()
        {
            Mortgage.Srv.IConfigSrv cfgSrv = Mortgage.Srv.SrvFactory.CreateConfigSrv();
            chkCalculate.DataSource = cfgSrv.GetAll("MORT_CAL_TYPE").OrderBy(m => m.SortOrder);
            chkCalculate.DataBind();

            chkCalculate.SelectedIndex = 0;
        }

        protected void BindMortStatusForBill()
        {
            rdoMortStatus.Items.Clear();
            Srv.IConfigSrv cfgSrv = Srv.SrvFactory.CreateConfigSrv();
            tzConfig cfgOnMortgage = cfgSrv.GetById((int)EnmMortgageStatus.OnMortgage);

            rdoMortStatus.Items.Add(new ListItem() { Text = cfgOnMortgage.Value, Value = cfgOnMortgage.ID.ToString() });

            tzConfig cfgDone = cfgSrv.GetById((int)EnmMortgageStatus.Done);
            rdoMortStatus.Items.Add(new ListItem() { Text = cfgDone.Value, Value = cfgDone.ID.ToString() });

            rdoMortStatus.SelectedIndex = 0;
        }

        protected void HandleFormStateBill(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:

                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;
                    btnEdit.Enabled = false;

                    BlankControlBill();
                    EnableControlBill(false);
                    EntityBill = new tBill() { ID = 0, BillDate = DateTime.Now, CalType = (int)EnmBillCalculateType.Week, BillType = (int)EnmMortgageStatus.Done };

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    btnEdit.Enabled = false;
                    EnableControlBill(true);
                    //fldStartDate.Enabled = false; // Edit can not delete

                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;
                    btnEdit.Enabled = false;
                    EnableControlBill(true);

                    break;
                case EnmFormMode.View:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;
                    btnEdit.Enabled = true;

                    EnableControlBill(false);
                    break;

            }

            BindViewBill();
        }

        protected void EnableControlBill(bool enable)
        {

            fldBillDate.Enabled = enable;
            fldBillMoney.Enabled = enable;
            fldDescription.Enabled = enable;

            chkCalculate.Enabled = enable;
            rdoMortStatus.Enabled = enable;
        }

        protected void RefreshDataGrid()
        {
            grid.DataSource = svcBill.GetByMortgageId(mortgageId);
            grid.DataBind();
        }

        protected void BindViewBill()
        {
            fldBillDate.Text = Utility.FormatDateTime(EntityBill.BillDate.GetValueOrDefault());
            fldDescription.Text = EntityBill.BillDescription;

            fldBillMoney.Text = (EntityBill.MoneyAmount.GetValueOrDefault() / 1000).ToString();

            if (EntityBill.BillType.HasValue)
                rdoMortStatus.SelectedValue = EntityBill.BillType.GetValueOrDefault().ToString();

            fldBillId.Value = EntityBill.ID.ToString();

            chkCalculate.SelectedValue = EntityBill.CalType.GetValueOrDefault().ToString();

            BuilCalculateFormula();

        }

        protected void BindViewMortgage()
        {
            if (EntityMorgate == null) return;

            fldInterestRate.Text = EntityMorgate.InterestRate.ToString();

            fldCustomerPhone.Text = EntityMorgate.CustomerPhone;
            fldCustumerAddress.Text = EntityMorgate.CustomerAddress;
            fldCustumerName.Text = EntityMorgate.CustomerName;
            fldDescription.Text = EntityMorgate.ItemDescription;
            fldItemName.Text = EntityMorgate.ItemName;

            fldMorDate.Text = Utility.FormatDateTime(EntityMorgate.MorDate.GetValueOrDefault());
            fldMorMoney.Text = Utility.FormatMoney(EntityMorgate.MorMoney);
            fldSerialNo.Text = EntityMorgate.SerialNo;

            fldStatus.Text = Utility.GetMorgageStatusCode(EntityMorgate.Status);
            if (EntityMorgate.Inter_ID != null)
            {
                Srv.IConfigSrv svcConf = Srv.SrvFactory.CreateConfigSrv();
                fldInterText.Text = svcConf.GetById(EntityMorgate.Inter_ID.GetValueOrDefault()).Value;
            }
            else
                fldInterText.Text = string.Empty;
        }

        protected void BindEntityBill()
        {
            EntityBill = new tBill();

            EntityBill.BillDescription = fldDescription.Text;
            EntityBill.MoneyAmount = Convert.ToDecimal(fldBillMoney.Text) * 1000;
            EntityBill.BillType = Convert.ToInt32(rdoMortStatus.SelectedValue);
            EntityBill.CalType = Convert.ToInt32(chkCalculate.SelectedValue);

            DateTime dteBillDate = new DateTime();
            if (Utility.ParseDateTime(fldBillDate.Text, out dteBillDate) == 0)
                EntityBill.BillDate = dteBillDate;
            EntityBill.ID = Convert.ToInt32(fldBillId.Value);

            EntityBill.MorID = EntityMorgate.ID;
            BindPropertyBill();
        }

        protected void BlankControlBill()
        {

            fldBillDate.Text = string.Empty;
            fldDescription.Text = string.Empty;
            fldBillMoney.Text = string.Empty;
            chkCalculate.ClearSelection();
            rdoMortStatus.ClearSelection();

        }

        protected void BindPropertyBill()
        {
            MembershipUser membershipUser = Membership.GetUser();

            if (membershipUser != null)
            {
                EntityBill.CreatedBy = membershipUser.UserName;
                EntityBill.ModifiedBy = membershipUser.UserName;

                EntityBill.CreatedDate = DateTime.Now;
                EntityBill.ModifiedDate = DateTime.Now;

                EntityBill.Age_ID = Utility.AgentId;

            }

        }

        #endregion



    }
}